package top.byfree.jbyan.saber.service

import cn.dev33.satoken.stp.StpUtil
import org.ktorm.dsl.eq
import org.ktorm.dsl.limit
import org.ktorm.dsl.map
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import top.byfree.jbyan.saber.bean.IS_DELETE_YES
import top.byfree.jbyan.saber.bean.Operate
import top.byfree.jbyan.saber.bean.Roles
import top.byfree.jbyan.saber.bean.dto.FilterPermDto
import top.byfree.jbyan.saber.bean.dto.PageDto
import top.byfree.jbyan.saber.bean.dto.PermDto
import top.byfree.jbyan.saber.bean.pojo.Perm
import top.byfree.jbyan.saber.bean.vo.UserVo
import top.byfree.jbyan.saber.common.IdWorker
import top.byfree.jbyan.saber.dao.PermDao
import java.time.LocalDateTime

/**
 * 权限业务处理层
 *
 * @author jbyan
 * @since 27/3/2024
 */
@Service
class PermService(
    @Autowired private val permDao: PermDao,
    @Autowired private val idWorker: IdWorker,
) {

    /** 根据权限编号查询权限信息 */
    fun getOne(permId: String) = permDao.findOne { it.permId eq permId }?.toVo()

    /** 条件分页查询权限信息 */
    fun page(size: Int, current: Int, filterPermDto: FilterPermDto): Any {
        // 通过 size 和 current 计算 offset 值
        val offset = size * current
        val query = permDao.filter(filterPermDto)
            .limit(offset, size)
        return PageDto(query.map(Roles::createEntity).map { it.toVo() }, query.totalRecordsInAllPages, current, size)
    }

    /** 添加权限信息 */
    fun add(permDto: PermDto) = permDao.add(permDto.toPerm(idWorker.nextId(), Operate.OPERATE_ADD)) > 0

    /** 更新权限信息 */
    fun update(permId: String, permDto: PermDto) = permDao.update(permDto.toPerm(permId, Operate.OPERATE_UPDATE)) > 0

    /** 逻辑删除权限信息 */
    fun delete(cRoleId: String) : Boolean {
        val userVo = (StpUtil.getSession().get("user") as? UserVo)!!
        val perm = Perm {
            permId = cRoleId
            isDelete = IS_DELETE_YES
            modifyBy = userVo.userId
            gmtModify = LocalDateTime.now()
        }
        return permDao.update(perm) > 0
    }
}